package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.reggie.config.common.CustomerException;
import com.itheima.reggie.config.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Name CategoryServiceImpl
 * @Author BaiXin
 * @Date 2022-10-31 10:16
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;
/*
    @Override
    public R deleteById(Long id) {
        //判断关联菜品数据
        Integer dishCount = dishMapper.selectCount(Wrappers.<Dish>lambdaQuery().eq(Dish::getCategoryId, id));
        if (dishCount>0) {
            //不能删除
            return R.error("此条数据有相关菜品，无法删除");
        }
        //判断关联套餐数据
        setmealMapper.selectCount(Wrappers.<Setmeal>lambdaQuery().eq(Setmeal::getCategoryId, id));
        if (dishCount>0) {
            //不能删除
            return R.error("此条数据有相关套餐，无法删除");
        }

        this.removeById(id);
        return R.success("分类删除成功");
    }*/

    @Override
    public R deleteById(Long id) {
        //判断关联菜品数据
        Integer dishCount = dishMapper.selectCount(Wrappers.<Dish>lambdaQuery().eq(Dish::getCategoryId, id));
        if (dishCount>0) {
            //不能删除
           throw new CustomerException("此条数据有相关菜品，无法删除");
        }
        //判断关联套餐数据
        setmealMapper.selectCount(Wrappers.<Setmeal>lambdaQuery().eq(Setmeal::getCategoryId, id));
        if (dishCount>0) {
            //不能删除
            throw new CustomerException("此条数据有相关套餐，无法删除");
        }

        this.removeById(id);
        return R.success("分类删除成功");
    }

    /**
     * 根据类型查询菜品或者套餐
     * @param type
     * @return
     */
    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> lqw = Wrappers.lambdaQuery(Category.class);

        // 设置条件
        lqw.eq(type!=null,Category::getType,type)
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);

        // 查询
        // 返回数据
        return this.list(lqw);
    }
}
